package com.xthh.picselect;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.xt.xthh.R;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_Faker;
import com.xthh._function.HH_FileUtil;
import com.xthh._function.HH_PicUtils;
import com.xthh._function.HH_SystemUtil;
import com.xthh._sort.HH_SortComparatorName;
import com.xthh._struct.HH_T_DIR_INFO;
import com.xthh._struct.HH_T_FolderSearch;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;


public class HH_AdapterFileSelectManage2 extends BaseAdapter {

    private static final String TAG = "AdapterFileSelectManage2";
    private Context context;
    private List<HH_T_FolderSearch> listFonts = new ArrayList<>();
    ArrayList<String> listExts = new ArrayList<>();
    private boolean getDetailsFolderInfo = false;



    private ImageView tempView = null;
    private final int MAX_DOWN_THREAD_COUNT = 10;
    private HashMap<String, Bitmap> bitmapHashMap = new HashMap<String, Bitmap>();
    private MyHendler myHendler = new MyHendler();
    // 加载图片线程
    List<List<String>> listLoadPic = new ArrayList<List<String>>();


    public HH_AdapterFileSelectManage2(Context context, ArrayList<String> exts, boolean useDetailsInfo) {
        this.context = context;
        listFonts = new ArrayList<>();
        listExts = exts;
        getDetailsFolderInfo = useDetailsInfo;

        // 设置10个线程同时下载
        for (int i = 0; i < MAX_DOWN_THREAD_COUNT; i++){
            listLoadPic.add(new ArrayList<>());
        }

        for (int i = 0; i < MAX_DOWN_THREAD_COUNT; i++){
            CreateLoadPicThread(i);
        }
    }


    private void CreateLoadPicThread(int index) {
        new Thread() {
            @Override
            public void run() {
                while (true){
                    if (listLoadPic.get(index) != null && listLoadPic.get(index).size() > 0){
                        String picPath = listLoadPic.get(index).get(0);
                        if (picPath != null && HH_FileUtil.IsExists(picPath)){
                            Bitmap bitmap = HH_PicUtils.GetBitmapFormFile(picPath);
                            if (bitmap != null){
                                bitmapHashMap.put(picPath, bitmap);
                                if (bitmap != null){
                                    myHendler.sendEmptyMessage(0);
                                }
                            }
                        }

                        // 删除这个
                        if (listLoadPic.get(index) != null && listLoadPic.get(index).size() > 0)
                            listLoadPic.get(index).remove(0);
                    }
                    HH_SystemUtil.Sleep(10);
                }
            }

        }.start();
    }

    public int GetFolderFiles(String path){
        ArrayList<File> files = new ArrayList<>();

        File rootFile = new File(path);
        HH_Faker faker = new HH_Faker();
        try {
            files = faker.computeAllFile(rootFile, new Function<File, Boolean>() {
                @Override
                public Boolean apply(File file) {
                    return HH_FileUtil.CheckFile(file.getPath(), listExts);
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (files != null){
            return files.size();
        }

        return 0;
    }


    public List<HH_T_FolderSearch> GetAll(){
        return listFonts;
    }
    public void addDevice(HH_T_FolderSearch tfs) {
        if (tfs == null)
            return;
        if (listFonts == null)
            listFonts = new ArrayList<>();

        listFonts.add(tfs);

        SortList();
    }

    public void addDevice_0(HH_T_FolderSearch tfs) {
        if (tfs == null)
            return;

        if (listFonts == null)
            listFonts = new ArrayList<>();


        if (listFonts.size() == 0){
            listFonts.add(tfs);
        } else {
            boolean bFind = false;
            for (int i = 0; i < listFonts.size(); i++){
                if (listFonts.get(i).isFile()){
                    listFonts.add(i, tfs);
                    bFind = true;
                    break;
                }
            }
            if (!bFind){
                listFonts.add(tfs);
            }
        }


        SortList();
    }

    private void SortList() {
        if (listFonts == null)
            return;


        List<HH_T_FolderSearch> folders = new ArrayList<>();
        List<HH_T_FolderSearch> files = new ArrayList<>();
        for (int i = 0; i < listFonts.size(); i++){
            if (listFonts.get(i).isFile())
                files.add(listFonts.get(i));
            else
                folders.add(listFonts.get(i));
        }


        Collections.sort(folders, new HH_SortComparatorName());
        Collections.sort(files, new HH_SortComparatorName());


        listFonts = new ArrayList<>();
        listFonts.addAll(folders);
        listFonts.addAll(files);
    }



    public void removeDevice(HH_T_FolderSearch bleDevice) {
        if (listFonts != null) {
            for (int i = 0; i < listFonts.size(); i++) {
                if (HH_CharUtil.Strcmp(listFonts.get(i).getPath(), bleDevice.getPath(), false)) {
                    listFonts.remove(i);
                    break;
                }
            }
        }
    }

    public void removeAll() {
        listFonts = new ArrayList<>();
    }


    @Override
    public int getCount() {
        return listFonts.size();
    }

    @Override
    public HH_T_FolderSearch getItem(int position) {
        if (position > listFonts.size())
            return null;
        return listFonts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView != null) {
            holder = (ViewHolder) convertView.getTag();
        } else {
            convertView = View.inflate(context, R.layout.adapter_pic_file_select, null);
            holder = new ViewHolder();
            convertView.setTag(holder);

            holder.textView_name = (TextView) convertView.findViewById(R.id.textView_name);
            holder.textView_res = (TextView) convertView.findViewById(R.id.textView_res);
            holder.linearlayout_select = convertView.findViewById(R.id.linearlayout_select);
            holder.linearlayout_bkg = convertView.findViewById(R.id.linearlayout_bkg);
            holder.imageView_icon = convertView.findViewById(R.id.imageView_icon);


            tempView = holder.imageView_icon;
        }

        final HH_T_FolderSearch ri = getItem(position);
        if (ri != null) {
            holder.textView_name.setText(ri.getPath());

            if (ri.getPath() != null){
                String[] split = ri.getPath().split("/");
                if (split != null && split.length > 0){
                    holder.textView_name.setText(split[split.length - 1]);
                }
            }

            if (ri.isSelect())
                holder.linearlayout_bkg.setBackgroundColor(Color.rgb(0xd3, 0xd3, 0xff));
            else
                holder.linearlayout_bkg.setBackgroundColor(Color.argb(0,0,0,0));

            if (ri.isFile()){

                HH_T_DIR_INFO di = HH_FileUtil.GetCurFileInfo(ri.getPath());
                if (HH_CharUtil.Strcmp(di.getExtN(), "bin", true)){
                    holder.imageView_icon.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_ota));
                    holder.textView_res.setText("");
                } else {
                    Bitmap bitmap = bitmapHashMap.get(ri.getPath());
                    if (bitmap == null){
                        LoadPicBitmap(ri.getPath());
                        SetTempIcon(holder.imageView_icon, ri.getPath());
                    } else {
                        holder.imageView_icon.setImageBitmap(bitmap);
                        holder.textView_res.setText(String.format("%d*%d", bitmap.getWidth(), bitmap.getHeight()));
                    }
                }

            } else {
                holder.imageView_icon.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.folder2));
                if (getDetailsFolderInfo)
                    holder.textView_res.setText(String.format("%d", ri.getFileCount()));
                else
                    holder.textView_res.setText("");
            }
        }


        holder.linearlayout_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.onSelect(ri, position);
                }

            }
        });

        holder.linearlayout_select.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (mListener != null) {
                    mListener.onSelectL(position);
                }
                return true;
            }
        });

        return convertView;
    }

    private void LoadPicBitmap(String picPath) {
        //listLoadPic.add(picPath);

        if (picPath == null || picPath.length() <= 0)
            return;
        if (listLoadPic == null || listLoadPic.size() <= 0)
            return;

        int[] numbers = new int[listLoadPic.size()];
        for (int i = 0; i < listLoadPic.size(); i++){
            if (listLoadPic.get(i) != null)
                numbers[i] = listLoadPic.get(i).size();
        }

        for (int i = 0; i < listLoadPic.size(); i++){
            List<String> lt = listLoadPic.get(i);
            if (lt != null){
                for (int j = 0; j < lt.size(); j++){
                    if (HH_CharUtil.Strcmp(lt.get(j), picPath, true)){
                        //Logging.i(TAG, new Exception(), "相同的任务取消:%s", fileUrl);
                        return;
                    }
                }
            }
        }


        // 排序
        //Logging.i(TAG, new Exception(), "src = %d,%d,%d,%d", numbers[0], numbers[1], numbers[2], numbers[3]);

        bubbleSort(numbers);

        //Logging.i(TAG, new Exception(), "dst = %d,%d,%d,%d", numbers[0], numbers[1], numbers[2], numbers[3]);

        if (numbers == null || numbers.length <= 0)
            return;

        for (int i = 0; i < listLoadPic.size(); i++){
            if (listLoadPic.get(i) != null){
                if (listLoadPic.get(i).size() == numbers[0]){
                    listLoadPic.get(i).add(picPath);
                    break;
                }
            }
        }
    }


    public static void bubbleSort(int[] array) {
        int n = array.length;
        boolean swapped;

        for (int i = 0; i < n - 1; i++) {
            swapped = false;

            for (int j = 0; j < n - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    // Swap elements
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                    swapped = true;
                }
            }

            if (!swapped) {
                break;
            }
        }
    }

    private void SetTempIcon(ImageView view, String path) {
        HH_T_DIR_INFO di = HH_FileUtil.GetCurFileInfo(path);
        if (HH_CharUtil.Strcmp(di.getExtN(), "png", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_png));
        } else if (HH_CharUtil.Strcmp(di.getExtN(), "jpg", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_jpg));
        } else  if (HH_CharUtil.Strcmp(di.getExtN(), "jpeg", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_jpg));
        } else if (HH_CharUtil.Strcmp(di.getExtN(), "bmp", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_bmp));
        } else if (HH_CharUtil.Strcmp(di.getExtN(), "gif", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_gif));
        } else if (HH_CharUtil.Strcmp(di.getExtN(), "bin", true)){
            view.setImageBitmap(HH_PicUtils.readBitmapById(context, R.drawable.icon_ota));
        }
    }


    class ViewHolder {
        ImageView imageView_icon;
        TextView textView_name;
        TextView textView_res;
        LinearLayout linearlayout_select;
        LinearLayout linearlayout_bkg;
    }

    public interface OnSelectListener {
        void onSelect(HH_T_FolderSearch deviceModel, int index);
        void onSelectL(int index);
    }

    private OnSelectListener mListener;

    public void setOnModelClickListener(OnSelectListener listener) {
        this.mListener = listener;
    }

    private class MyHendler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    notifyDataSetChanged();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    }
}
